import { HOT_CONCEPTS, HOT_INDUSTRIES, FIVE_DAY_HOT_SECTORS } from './constants'

const MARKET_STOCKS = [
  { 
    code: '600519'
   
  },
  { 
    code: '00700'
   
  },
  { 
    code: '09988'
   
  },
  { 
    code: '600960'
   
  },
  { 
    code: '002479'
 
  },
  { 
    code: '605287'
   
  },
  { 
    code: '300766'
  
  },
  { 
    code: '688217'
  }
];

// 提取股票代码
const STOCK_CODES = MARKET_STOCKS.map(stock => stock.code);

Page({
  data: {
    isLoggedIn: false,
    showUserMenu: false,
    // 日期信息
    year: '',
    month: '',
    day: '',
    weekDay: '',
    // 热门概念和行业数据
    hotConcepts: [],
    hotIndustries: [],
    fiveDayHotSectors: [],
    // 板块切换tabs
    sectorTabs: ['热门概念', '热门行业', '5日涨幅最大'],
    currentTab: 0,
    // 股票排行tab
    rankTabs: ['涨幅榜', '跌幅榜', '成交额', '涨速榜'],
    currentRankTab: 0,
    rankList: {
      upList: [],
      downList: [],
      volumeList: [],
      speedList: [],
    },
    // 在data中存储从 market.js 复制过来的基础股票数据，但实际排行榜会用获取的实时数据覆盖
    // baseStocks: MARKET_STOCKS, 
  },

  // 页面加载生命周期
  onLoad() {
    this.checkLoginStatus()
    this.initDateInfo()
    this.initSectorsData()
    this.getRankListData() // Fetch real rank data on load
    console.log('行情页加载完成')
  },

  onShow() {
    // 页面显示/从后台切回
    this.checkLoginStatus()
    console.log('行情页显示')
  },

  // 初始化板块数据
  initSectorsData() {
    this.setData({
      hotConcepts: HOT_CONCEPTS,
      hotIndustries: HOT_INDUSTRIES,
      fiveDayHotSectors: FIVE_DAY_HOT_SECTORS
    })
  },

  // 初始化日期信息
  initDateInfo() {
    const date = new Date()
    const weekDays = ['日', '一', '二', '三', '四', '五', '六']
    
    this.setData({
      year: date.getFullYear(),
      month: date.getMonth() + 1,
      day: date.getDate(),
      weekDay: weekDays[date.getDay()]
    })
  },
  // 股票排行tab切换
  switchRankTab(e) {
    const index = e.currentTarget.dataset.index
    this.setData({ currentRankTab: index })
  },
  
  // 板块tab切换
  switchTab(e) {
    this.setData({
      currentTab: e.currentTarget.dataset.index
    })
  },

  async checkLoginStatus() {
    console.log('正在检查登录状态...');
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo && userInfo.phone && userInfo.openid) { // Ensure essential info exists
      console.log('本地存在userInfo:', userInfo);
      try {
        const { result } = await wx.cloud.callFunction({
          name: 'user',
          data: {
            type: 'checkStatus',
            phone: userInfo.phone,
            // openid now handled in cloud function using getWXContext
          }
        })

        console.log('checkStatus 云函数返回:', result);

        if (result.success && result.isLoggedIn) {
          this.setData({
            isLoggedIn: true
          })
          console.log('登录状态更新为: true');
        } else {
          console.log('登录状态检查失败或未登录，清除本地userInfo');
          wx.removeStorageSync('userInfo')
          this.setData({
            isLoggedIn: false
          })
          console.log('登录状态更新为: false');
        }
      } catch (error) {
        console.error('检查登录状态云函数调用失败:', error)
        // Even if cloud function call fails, assume not logged in if userInfo exists but check failed
        this.setData({
          isLoggedIn: false
        })
        console.log('登录状态更新为: false (云函数调用失败)');
      }
    } else {
      console.log('本地不存在userInfo，或信息不完整，视为未登录');
      this.setData({
        isLoggedIn: false
      })
       console.log('登录状态更新为: false (本地无userInfo)');
    }
  },

  showUserMenu() {
    console.log('showUserMenu 被调用，当前 isLoggedIn:', this.data.isLoggedIn);
    if (!this.data.isLoggedIn) {
      console.log('未登录，尝试跳转到登录页面');
      this.navigateToLogin()
      return
    }
    console.log('已登录，尝试显示用户菜单');
    this.setData({
      showUserMenu: true
    })
  },

  hideUserMenu() {
    this.setData({
      showUserMenu: false
    })
  },

  stopPropagation() {
    // 阻止事件冒泡
  },

  navigateToLogin() {
    console.log('尝试跳转到登录页面...');
    wx.navigateTo({
      url: '/pages/login/login',
      success: function() {
        console.log('跳转到登录页面成功');
      },
      fail: function(err) {
        console.error('跳转到登录页面失败:', err);
      }
    })
  },

  switchPhone() {
    this.hideUserMenu()
    this.navigateToLogin()
  },

  async handleLogout() {
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) return

    try {
      const { result } = await wx.cloud.callFunction({
        name: 'user',
        data: {
          type: 'logout',
          phone: userInfo.phone
        }
      })

      if (result.success) {
        wx.removeStorageSync('userInfo')
        this.setData({
          isLoggedIn: false,
          showUserMenu: false
        })
        wx.showToast({
          title: '退出登录成功',
          icon: 'success'
        })
      }
    } catch (error) {
      wx.showToast({
        title: '退出登录失败',
        icon: 'none'
      })
    }
  },

  // Add method to navigate to stock detail page
  navigateToStockDetail(e) {
    const code = e.currentTarget.dataset.code;
    const name = e.currentTarget.dataset.name;
    wx.navigateTo({
      url: `/pages/stock-detail/index?code=${code}&name=${name}`
    })
  },

  // Helper method to format volume (copied from stock-detail/index.js)
  formatVolume: function(num) {
    if (num === undefined || num === null) return '0';

    num = parseFloat(num);
    if (isNaN(num)) return '0';

    if (num >= 100000000) {
      return (num / 100000000).toFixed(2) + '亿';
    } else if (num >= 10000) {
      return (num / 10000).toFixed(2) + '万';
    } else {
      return num.toFixed(0);
    }
  },

  // Method to fetch and parse stock real-time data for a list of codes
  async fetchAndParseStockData(codes) {
    if (!codes || codes.length === 0) {
      return [];
    }

    const fullCodes = codes.map(code => {
      const prefix = code.startsWith('6') ? 'sh' : 'sz';
      return prefix + code;
    }).join(',');

    return new Promise((resolve, reject) => {
      wx.request({
        url: `https://hq.sinajs.cn/list=${fullCodes}`,
        header: {
          'content-type': 'application/json',
          'Referer': 'https://finance.sina.com.cn'
        },
        success: (res) => {
          if (res.data) {
            const results = res.data.split(';').filter(item => item.includes('var hq_str_')).map(item => {
              try {
                const dataStr = item.split('="')[1].split('";')[0];
                const elements = dataStr.split(',');
                
                if (elements.length > 1) {
                  // 获取当前价格和昨收价
                  const currentPrice = parseFloat(elements[3]);
                  const yesterdayClose = parseFloat(elements[2]);
                  
                  // 计算涨跌额和涨跌幅
                  const priceChange = (currentPrice - yesterdayClose);
                  const changePercent = ((priceChange / yesterdayClose) * 100);
                  
                  // 获取成交量（手）
                  const volume = parseFloat(elements[8]) / 100;
                  
                  // 获取成交额（元）
                  const amount = parseFloat(elements[9]);

                  // 处理股票代码，去掉所有非数字字符
                  const rawCode = item.split('="')[0].replace('var hq_str_', '');
                  const code = rawCode.replace(/[^\d]/g, ''); // 移除非数字字符

                  return {
                    code: code,
                    name: elements[0],
                    currentPrice: currentPrice.toFixed(2),
                    priceChange: priceChange > 0 ? '+' + priceChange.toFixed(2) : priceChange.toFixed(2),
                    changePercent: changePercent > 0 ? '+' + changePercent.toFixed(2) + '%' : changePercent.toFixed(2) + '%',
                    volume: this.formatVolume(volume),
                    amount: amount,
                    // 用于排序的原始数据
                    _priceChange: priceChange,
                    _changePercent: changePercent,
                    _amount: amount
                  };
                }
              } catch (e) {
                console.error('解析股票数据出错:', e, 'data:', item);
              }
              return null;
            }).filter(item => item !== null);
            
            console.log('解析后的股票数据:', results);
            resolve(results);
          } else {
            resolve([]);
          }
        },
        fail: (err) => {
          console.error('获取股票数据失败:', err);
          reject(err);
        }
      });
    });
  },

  // Modified method to get rank list data
  async getRankListData() {
    wx.showLoading({
      title: '加载排行...'
    });
    try {
      const realTimeStocks = await this.fetchAndParseStockData(STOCK_CODES);
      console.log('获取到的实时股票数据:', realTimeStocks);

      if (realTimeStocks.length === 0) {
        throw new Error('未获取到股票数据');
      }

      // 根据涨跌幅排序
      const sortedByChange = [...realTimeStocks].sort((a, b) => b._changePercent - a._changePercent);
      
      // 涨幅榜：取涨幅最大的前3只
      const upList = sortedByChange.slice(0, 3);
      
      // 跌幅榜：取跌幅最大的前3只（涨幅最小的）
      const downList = sortedByChange.slice(-3).reverse();
      
      // 成交额榜：按成交额排序取前3只
      const volumeList = [...realTimeStocks]
        .sort((a, b) => b._amount - a._amount)
        .slice(0, 3);

      console.log('涨幅榜:', upList);
      console.log('跌幅榜:', downList);
      console.log('成交额榜:', volumeList);

      this.setData({
        rankList: {
          upList: upList,
          downList: downList,
          volumeList: volumeList,
          speedList: [] // 暂时不实现涨速榜
        }
      });
      
      wx.hideLoading();
    } catch (error) {
      console.error('获取股票排行数据失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: '获取排行数据失败',
        icon: 'none',
      });
      this.setData({
        rankList: { 
          upList: [], 
          downList: [], 
          volumeList: [], 
          speedList: [] 
        }
      });
    }
  },
})